/*
 * @(#)ContentsController.java $version 2012. 5. 24.
 *
 */

package com.mywep.myalimi.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mywep.myalimi.model.User;
import com.mywep.myalimi.model.url.ContentsUrlParam;
import com.mywep.myalimi.service.ContentsService;

import com.nhncorp.lucy.spring.core.util.DataMap;
import com.nhncorp.lucy.spring.core.util.ExtendedMap;

/**
 * @author 한지웅
 */
@Controller
@RequestMapping("/alimi/contents")
public class ContentsController {
	@Autowired
	private ContentsService contentsService;

	@RequestMapping(value = "/getNew.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView getNewContents(HttpServletRequest request, ContentsUrlParam urlParam) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");
		mav.addAllObjects(contentsService.getNewContents(user, urlParam));
		mav.setViewName("contents/newlist");
		return mav;
	}

	@RequestMapping(value = "/getUser.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView getUserContents(HttpServletRequest request, ContentsUrlParam urlParam) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");
		mav.addAllObjects(contentsService.getUserContents(user, urlParam));
		mav.setViewName("contents/userlist");
		return mav;
	}

	@RequestMapping(value = "/save.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView getSave(HttpServletRequest request, ContentsUrlParam urlParam) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");
		contentsService.txSaveUserContent(user, urlParam);
		mav.addObject("keyword", urlParam.getKeyword());
		mav.setViewName(String.format("redirect:%s", "/alimi/contents/getNew.alm"));
		return mav;
	}

	@RequestMapping(value = "/delete.json", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView getDelete(HttpServletRequest request, ContentsUrlParam urlParam) throws UnsupportedEncodingException {
		ModelAndView mav = new ModelAndView();
		ExtendedMap message = new DataMap();

		User user = (User)request.getAttribute("user");
		try {
			if (user != null && StringUtils.isNotBlank(user.getId())) {
				contentsService.txDeleteUserContent(urlParam);
				message.put("result", "success");
			} else {
				message.put("result", "fail");
			}
		} catch (Exception e) {
			message.put("result", "fail");
		}
		mav.addObject("message", message);
		return mav;
	}
	
	
}
